package org.knight.gearbox;

import org.knight.gearbox.security.CustomMethodSecurityMetadataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor;
import org.springframework.security.access.vote.AffirmativeBased;
import org.springframework.security.access.vote.RoleVoter;
import org.springframework.security.authentication.AuthenticationManager;

import java.util.Arrays;


@EnableJpaRepositories(basePackages={"org.knight"})
//@EnableJpaRepositories(basePackages={"dao层对应的包路径"})
@ComponentScan(value={"org.knight"})//扫描组件 @ComponentScan(value = "com.spriboot.controller") 配置扫描组件的路径
@SpringBootApplication
//@EntityScan("entity对应的包路径")
@EntityScan("org.knight.gearbox.model.entity")
public class GearboxApplication {


	@Bean
	public AccessDecisionVoter accessDecisionVoter() {
		RoleVoter roleVoter = new RoleVoter();
		roleVoter.setRolePrefix("");
		return roleVoter;
	}


	@Bean
	public AccessDecisionManager accessDecisionManager(AccessDecisionVoter voter) {
		return new AffirmativeBased(Arrays.asList(voter));
	}

	@Bean
	public MethodSecurityInterceptor methodSecurityInterceptor(AuthenticationManager authenticationManager, AccessDecisionManager adm, CustomMethodSecurityMetadataSource metadataSource) {
		MethodSecurityInterceptor interceptor = new MethodSecurityInterceptor();
		interceptor.setSecurityMetadataSource(metadataSource);
		interceptor.setAccessDecisionManager(adm);
		interceptor.setAuthenticationManager(authenticationManager);
		interceptor.setRejectPublicInvocations(true);
		return  interceptor;
	}

	public static void main(String[] args) {
		SpringApplication.run(GearboxApplication.class, args);
	}

}
